package com.nbc.car.biz.service.impl;

import com.nbc.car.biz.dao.IUserDAO;
import com.nbc.car.biz.entity.CUser;
import com.nbc.car.biz.entity.Token;
import com.nbc.car.biz.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

/**
 * Created by nipin on 16/7/21.
 */
@Service
public class UserServiceImpl implements IUserService {
    @Autowired
    private IUserDAO iUserDAO;
    private final String salt = "nbc-20160610!@#$";
    private final int ttl = 30; //一个token的过期时间默认为30分钟
    @Override
    public CUser login(CUser cUser) {
        return iUserDAO.login(cUser);
    }
    @Override
    @Transactional(rollbackFor={RuntimeException.class,Exception.class},propagation = Propagation.REQUIRED)
    public boolean register(CUser cUser) {
        int registerCount = iUserDAO.register(cUser);
        System.out.println("---:"+cUser);
        if (registerCount == 1){    //当创建用户成功时,再去生成,插入令牌
            String phone = cUser.getPhone();
            String tokenMD5 = this.makeToken(phone);
            Token token = cUser.getToken();
            token.setUserId(cUser.getcUserId());
            token.setToken(tokenMD5);
            int insertTokenCount = iUserDAO.createToken(token);
            if (insertTokenCount == 1){
                return true;
            }
        }
        return false;
    }

    private String makeToken(String origin){
        String base = origin + salt;
        return DigestUtils.md5DigestAsHex(base.getBytes());
    }
}
